package com.adulcimer.utils;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;

/**
 * 树形工具类
 */
public class TreeUtils {
    /**
     * 列表对象转树形对象
     *
     * @param list              列表对象
     * @param parentIdExtractor 父级ID字段
     * @param childrenSetter    子级字段
     * @param idExtractor       ID字段
     * @param parentId          父级ID
     * @param <T>               入参泛型
     * @param <U>               父级ID类型
     * @return 子级列表
     */
    public static <T, U> List<T> listToTree(List<T> list, Function<T, U> parentIdExtractor, Setter<T, List<T>> childrenSetter, Function<T, U> idExtractor, U parentId) {
        if (Objects.isNull(list)) {
            return List.of();
        }
        List<T> children = list.stream().filter(data -> Objects.equals(parentIdExtractor.apply(data), parentId)).toList();
        children.forEach(child -> childrenSetter.accept(child, listToTree(list, parentIdExtractor, childrenSetter, idExtractor, idExtractor.apply(child))));
        return children;
    }

    @FunctionalInterface
    public interface Setter<T, P> {
        void accept(T t, P p);
    }
}
